package net.zdreamer.geracomium.utils.PersonalinfoUtils;

import java.util.ArrayList;

import net.zdreamer.geracomium.adapter.TreeLeafAdapter;
import net.zdreamer.geracomium.ui.more.EditAdressActivity;
import net.zdreamer.geracomium.utils.file.getAdress;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;


public class TreeLeafItemClickListener implements OnItemClickListener {

    private TreeLeafAdapter leafAdapter;
    private Context context;
    private ArrayList<LeafDao> elementsData;
    private ArrayList<LeafDao> elements;
    public String Name, Index, source;
    public String Province="",City="",Zone="";
    LeafDao element;
    private LayoutInflater inflater;
    StringBuffer addres = new StringBuffer();

    public TreeLeafItemClickListener(TreeLeafAdapter leafAdapter,
                                     Context context, String index, String source) {
        this.leafAdapter = leafAdapter;
        this.context = context;
        this.Index = index;
        this.source = source;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {


        element = (LeafDao) leafAdapter.getItem(position);
        elements = leafAdapter.getElements();
        elementsData = leafAdapter.getElementsData();



        Name = element.getContentText().getName().toString();
        findByProviceName(Name, context, position);
        leafAdapter.setElements(elements);
        leafAdapter.notifyDataSetChanged();

        findByName(Name, context, position);
        leafAdapter.setElements(elements);
        leafAdapter.notifyDataSetChanged();
        if (element.getLevel() == 0) {
            Province = Name;
        } else if (element.getLevel() == 1) {
            City = Name;
        } else if (element.getLevel() == 2) {
            Zone = Name;
        }
        String address = Province+City+Zone;
        System.out.println(address);
        if (!element.isHasChildren()) {
            Intent intent = new Intent(context, EditAdressActivity.class);
            intent.putExtra("address", address);
            intent.putExtra("index", Index);
            intent.putExtra("source", source);
            context.startActivity(intent);
            ((Activity) context).finish();
            addres.delete(0, addres.length());

            return;
        }

        if (element.isExpanded()) {
            element.setExpanded(false);
            addres.delete(0, addres.length());
            ArrayList<LeafDao> elementsToDel = new ArrayList<LeafDao>();
            for (int i = position + 1; i < elements.size(); i++) {
                if (element.getLevel() >= elements.get(i).getLevel())
                    break;
                elementsToDel.add(elements.get(i));
            }
            elements.removeAll(elementsToDel);
            leafAdapter.notifyDataSetChanged();
        } else {
            element.setExpanded(true);
            int i = 1;
            for (LeafDao e : elementsData) {
                if (e.getParendId() == element.getId()) {
                    e.setExpanded(false);
                    elements.add(position + i, e);

                    i++;
                }

            }
            leafAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 得到点击的省的名字
     */
    public void findByProviceName(String name, Context context, int position) {
        getAdress sql = new getAdress();
        SQLiteDatabase db;
        db = sql.openDatabase(context);
        Cursor cursor = db.query("T_Province", null, "ProName=?",
                new String[]{name}, null, null, null);
        StringBuffer text = new StringBuffer();
        if (cursor != null && cursor.moveToFirst()) {
            // person = new Person();
            int i = cursor.getInt(cursor.getColumnIndexOrThrow("ProSort"));

            findByProviceId(i, context, position);
        }
    }

    /**
     * 根据省的名字得到其中城市的名字，并加入列表
     */
    public void findByProviceId(int id, Context context, int position) {
        getAdress sql = new getAdress();
        SQLiteDatabase db;
        db = sql.openDatabase(context);
        Cursor cursor = db.query("T_City", null, "ProID=?",
                new String[]{String.valueOf(id)}, null, null, null);
        StringBuffer text = new StringBuffer();
        int i = 1;
        while (cursor.moveToNext()) {
            String city = cursor.getString(cursor
                    .getColumnIndexOrThrow("CityName"));
            LeafDao e4 = new LeafDao(new Leaf(city, 4), LeafDao.TOP_LEVEL + 1,
                    3, id, true, false);
            elements.add(position + 1, e4);
            i++;
        }
        db.close();
    }

    /**
     * 得到点击的省城市的名字
     */
    public void findByName(String name, Context context, int position) {
        getAdress sql = new getAdress();
        SQLiteDatabase db;
        db = sql.openDatabase(context);
        Cursor cursor = db.query("T_City", null, "CityName=?",
                new String[]{name}, null, null, null);
        StringBuffer text = new StringBuffer();
        if (cursor != null && cursor.moveToFirst()) {
            // person = new Person();
            int i = cursor.getInt(cursor.getColumnIndexOrThrow("CitySort"));

            findById(i, context, position);
        }
    }

    /**
     * 根据省的名字得到其中城市的名字，并加入列表
     */
    public void findById(int id, Context context, int position) {
        getAdress sql = new getAdress();
        SQLiteDatabase db;
        db = sql.openDatabase(context);
        Cursor cursor = db.query("T_Zone", null, "CityID=?",
                new String[]{String.valueOf(id)}, null, null, null);
        StringBuffer text = new StringBuffer();
        int i = 1;
        while (cursor.moveToNext()) {
            String city = cursor.getString(cursor
                    .getColumnIndexOrThrow("ZoneName"));
            LeafDao e4 = new LeafDao(new Leaf(city, 4), LeafDao.TOP_LEVEL + 2,
                    3, id, false, false);
            elements.add(position + 1, e4);
            i++;
        }
        db.close();
    }

    public String getText(String text) {

        addres.append(text);
        return addres.toString();

    }
}
